package com.zx.lc.config;

import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.listener.ChatModelErrorContext;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import dev.langchain4j.model.chat.listener.ChatModelRequestContext;
import dev.langchain4j.model.chat.listener.ChatModelResponseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
class MyConfiguration {

    /**
     * 模型事件监听器：要启用ChatLanguageModel或StreamingChatLanguageModel bean 的可观察性
     * @return
     */
    @Bean
    public ChatModelListener chatModelListener() {
        return new ChatModelListener() {

            @Override
            public void onRequest(ChatModelRequestContext requestContext) {
                log.info("onRequest(): {}", requestContext.chatRequest());
            }

            @Override
            public void onResponse(ChatModelResponseContext responseContext) {
                log.info("onResponse(): {}", responseContext.chatResponse());
            }

            @Override
            public void onError(ChatModelErrorContext errorContext) {
                log.info("onError(): {}", errorContext.error().getMessage());
            }
        };
    }

    /**
     * 在内存中记录会话上下文。
     * @return
     */
    @Bean("myChatMemory")
    public ChatMemory chatMemory() {
        return MessageWindowChatMemory.withMaxMessages(100);
    }

    @Bean("myChatMemoryProvider")
    public ChatMemoryProvider chatMemoryProvider() {
        return new ChatMemoryProvider() {
            private static final RedisChatStore CHAT_STORE = new RedisChatStore();

            @Override
            public ChatMemory get(Object o) {
                log.info("获得ChatMemory, memoryId={}", o);

                return MessageWindowChatMemory
                        .builder()
                        .id(o)
                        // 每个用户只记录5条会话。
                        .maxMessages(5)
                        // 这里可以自定义存储的位置，实现ChatMemoryStore，例如redis。
                        .chatMemoryStore(CHAT_STORE)
                        .build();
            }
        };
    }
}
